package cn.wongshu.student.service;

import cn.wongshu.student.dao.CategoryDao;
import cn.wongshu.student.pojo.Category;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

/**
 * @author:jayChou
 * @date:2019/7/19 description:神来之手
 * 动态获取菜单
 */
@Service
@Transactional
public class CategoryService {

    @Autowired(required = false)
    private CategoryDao categoryDao;

    public List<Category> findAll() {
        Example example = new Example(Category.class);
        Example.Criteria criteria = example.createCriteria();
        example.orderBy("level").asc();
        criteria.andEqualTo("delFlag","0");
        return categoryDao.selectByExample(example);

    }

    public void save(Category category) {
        category.setCreateDate(new Date());
        category.setGoodsCount(0);
        this.changeGoodsLevel(category);
        categoryDao.insertSelective(category);

    }

    private void changeGoodsLevel(Category category) {
        categoryDao.changeAfterLevel(category.getLevel());
        category.setLevel(category.getLevel()+1);

    }

    public Category findById(Integer id) {
        return categoryDao.selectByPrimaryKey(id);
    }

    public List<Category> search(Category category) {
      return categoryDao.search(category);
    }



    public void deleteByIds(Integer[] ids) {

        categoryDao.deleteByBatch(ids);

    }

    public void update(Category category) {
        category.setUpdateDate(new Date());
        this.changeGoodsLevel(category);
        categoryDao.updateByPrimaryKeySelective(category);
    }

    public int getLevel() {
        Example example = new Example(Category.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("delFlag",0);
        return categoryDao.selectCountByExample(example);
    }
}
